import type { EChartsOption } from 'echarts';
import * as echarts from 'echarts';
import { debounce, isElement } from 'lodash-es';
import chinaJson from './components/geojson.json';

export const useCharts = (el: Ref<HTMLDivElement>) => {
	const chart = shallowRef<echarts.ECharts>();
	/** 是否开启双击事件 */
	const resizeFn = debounce(resize, 200);
	echarts.registerMap('china', chinaJson as any);

	/** 初始化echarts */
	const initCharts = () => {
		if (!isElement(el.value)) {
			return;
		}
		chart.value = echarts.init(el.value);
	};

	/** 设置图例option */
	const setOption = async (opts: EChartsOption) => {
		if (!chart.value) {
			initCharts();
		}
		await nextTick();
		chart.value?.setOption(opts);
	};

	/** 重新绘制 */
	function resize() {
		chart.value?.resize();
	}

	useResizeObserver(el, (entries) => {
		resizeFn();
	});


	onMounted(() => {
		initCharts();
	});

	onBeforeUnmount(() => {
		chart.value?.dispose();
	});

	return {
		chart,
		setOption,
		resize,
	};
};
